package com.jule.miaozhuapc.servlet;

import com.jule.miaozhuapc.domain.WawaPay;
import com.jule.miaozhuapc.domain.WawaRecharge;
import com.jule.miaozhuapc.service.PayService;
import com.jule.miaozhuapc.service.RechargeService;
import com.jule.miaozhuapc.util.Const;
import com.jule.miaozhuapc.util.WxComUtil;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.PingppObject;
import com.pingplusplus.model.Webhooks;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/WxPaySucServlet")
public class WxPaySucServlet extends HttpServlet {

    @Autowired
    RechargeService rechargeService;
    @Autowired
    PayService payService;
    private Logger logger = Logger.getLogger(this.getClass());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF8");
        //获取头部所有信息
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            System.out.println(key+" "+value);
        }
        // 获得 http body 内容
        BufferedReader reader = request.getReader();
        StringBuffer buffer = new StringBuffer();
        String string;
        while ((string = reader.readLine()) != null) {
            buffer.append(string);
        }
        reader.close();
        // 解析异步通知数据
        logger.info(buffer.toString());
        Map<String, String> map = new HashMap<String, String>();
        try {
            map = WxComUtil.doXMLParse(buffer.toString());
        } catch (Exception e) {
            logger.error("doXMLParse()--error", e);
        }

        //解决Autowired为null无法注入问题
        if (rechargeService == null || payService == null) {
            WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);
        }
        //成功
        if (map.get("return_code").equalsIgnoreCase("SUCCESS")) {
            try {
                String order_no = map.get("out_trade_no");
                WawaRecharge wawaRecharge = rechargeService.findByOrderNo(order_no);
                if (wawaRecharge != null && (wawaRecharge.getSucTime()== null || "".equals(wawaRecharge.getSucTime()))) {
                    wawaRecharge.setSucTime(new Date());
                    wawaRecharge.setStatus(1);
                    rechargeService.update(wawaRecharge);

                    //addCoin
                    WawaPay pay = new WawaPay();
                    pay.setAddTime(new Date());
                    pay.setCoin(wawaRecharge.getCoin());
                    pay.setIsDelete(false);
                    pay.setMoney(wawaRecharge.getMoney());
                    pay.setRemark("充值");
                    pay.setType(Const.WAWA_PAY_TYPE_MONEY);
                    pay.setUserId(wawaRecharge.getUserId());
                    pay.setRechargeId(wawaRecharge.getId());

                    payService.addCoin(pay);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else {
            logger.info("充值失败");
        }
        // 给wx 成功通知
        String outputStr = "<xml> "
                + "<return_code><![CDATA[SUCCESS]]></return_code>"
                +" <return_msg><![CDATA[OK]]></return_msg>"
                + " </xml>";
        PrintWriter out = response.getWriter();
        out.print(outputStr.toString());
        out.flush();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);
    }
}
